package com.itmk.web.sys_major.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.sys_major.entity.Major;
import com.itmk.web.sys_major.entity.MajorParm;
import com.itmk.web.sys_major.entity.SelectMajor;
import com.itmk.web.sys_major.service.MajorService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author java实战基地
 * @since 2023-10-08
 */
@RestController
@RequestMapping("/api/major")
public class MajorController {
    @Autowired
    private MajorService majorService;

    //新增
    @PostMapping
    public ResultVo add(@RequestBody Major major){
        if(majorService.save(major)){
            return ResultUtils.success("新增成功");
        }
        return ResultUtils.error("新增失败!");
    }

    //编辑
    @PutMapping
    public ResultVo edit(@RequestBody Major major){
        if(majorService.updateById(major)){
            return ResultUtils.success("编辑成功");
        }
        return ResultUtils.error("编辑失败!");
    }

    //删除
    @DeleteMapping("/{majorId}")
    public ResultVo delete(@PathVariable("majorId") Integer majorId){
        if(majorService.removeById(majorId)){
            return ResultUtils.success("删除成功");
        }
        return ResultUtils.error("删除失败!");
    }

    //列表
    @GetMapping("/list")
    public ResultVo getList(MajorParm parm){
        //构造分页对象
        IPage<Major> page = new Page<>(parm.getCurrentPage(),parm.getPageSize());
        //构造查询条件
        QueryWrapper<Major> query = new QueryWrapper<>();
        //传递参数，才做模糊查询
        if(StringUtils.isNotEmpty(parm.getMajorName())){
            query.lambda().like(Major::getMajorName,parm.getMajorName());
        }
        //排序:根据orderNum字段排序
        query.lambda().orderByDesc(Major::getOrderNum);
        IPage<Major> list = majorService.page(page, query);
        return ResultUtils.success("查询成功",list);
    }

    //专业下拉数据
    @GetMapping("/select")
    public ResultVo select(){
        List<Major> list = majorService.list();
        List<SelectMajor> selectMajors = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .forEach(item ->{
                    SelectMajor major = new SelectMajor();
                    major.setLabel(item.getMajorName());
                    major.setValue(item.getMajorId());
                    selectMajors.add(major);
                });
        return ResultUtils.success("查询成功",selectMajors);
    }
}

